const Koa = require('koa');
const http = require('http');
const app = new Koa();
const router = require('koa-router')();
const co = require('co');
const convert = require('koa-convert');
const json = require('koa-json');
const onerror = require('koa-onerror');
const logger = require('koa-logger');
const session = require('koa-session');
const koaBody = require('koa-body');
const db = require('./src/models/db');
const Utils = require('./src/controllers/utils');
const Nexmo = require('./src/controllers/utils/nexmo');
const schedule = require('node-schedule');
const ClientModel = require('./src/models/nexmo/client.model');
const rentalModel = require('./src/models/nexmo/rental.model');
import {frontendRouter,serverRouter} from './src/router';
onerror(app);
// cookies
app.keys = ['eycms:secret'];
const CONFIG = {
  key: 'eycms', 
  maxAge: 604800000,  // 7天
  overwrite: true, 
  signed: true, 
};
app.use(koaBody({
      multipart:true,
      formLimit:104857600,
      formidable:{
        maxFieldsSize: 104857600
      }
    }))
   .use(convert(logger()))
   .use(convert(session(CONFIG,app)))
   .use(convert(require('koa-static')(__dirname + '/public')));

app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
// router
app.use(require('./src/middleware/response'))
  .use(require('./src/middleware/filter'))
  .use(serverRouter.routes())
	.use(serverRouter.allowedMethods())
  .use(frontendRouter.routes())
  .use(frontendRouter.allowedMethods());
// response
app.on('error', function(err, ctx){
  logger.error('server error', err, ctx);
  ctx.render('error', { message: ' 服务器错误!',error: err });
});

// 每天凌晨12点定时任务

var rule  = new schedule.RecurrenceRule();
var times  = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17.18,19,20,21,22,23];
rule.hour  = times;
rule.minute = 0;
// 正常扣费
var setDeduction = function(item, isNormal) {
  var currDateToDay = Utils.currDateToDay(new Date(), new Date(item.nextBillingDate))
  var oweDateToDay =item.oweDay && Utils.currDateToDay(new Date(), new Date(item.oweDate))
  var _monthPrice = item.monthPrice || item.country.monthPrice
  var _price = Utils.decimal(parseFloat(item.remainingMoney), parseFloat(_monthPrice), 'sub')
  var _profits = Utils.decimal(parseFloat(_monthPrice),parseFloat(item.cost), 'sub') + ''
  console.log(currDateToDay,oweDateToDay, item.nextBillingDate)
  // 正常扣费
  var options = {
    nextBillingDay: isNormal ? Utils.currDateTo30() : parseInt(currDateToDay) <= 0 ? oweDateToDay: currDateToDay,
  }
  if (isNormal) {
    options.remainingMoney = _price
    options.nextBillingDate = new Date(); 
    options.oweDay = 0
  } else {
     //如果是余额为负数且欠费天数大于1就增加欠费天数
    if (item.remainingMoney < 0 && item.oweDay >= 0) {
      options.oweDay = !oweDateToDay ? 1 : oweDateToDay
    }
    // 有余额的时候再扣一次
    if(item.remainingMoney > 0 && item.oweDay > 0) { 
      options.remainingMoney = _price
      options.nextBillingDay =  30
      options.oweDay = 0
      options.nextBillingDate = new Date();
    }
  }
  ClientModel.updateOne({_id: item._id}, {$set:options}, function(err,data) {
      console.log(err, data)
  })
  if (isNormal) {
    // 记录月租数据统计
    rentalModel.create({
        msisdn: item.msisdn,
        // 月租成本
        cost: item.cost,
        //国家代码
        dialingPrefix: item.country.dialingPrefix,
        // 区域
        countryName:item.country.countryName,
        // 月租价格
        monthPrice: _monthPrice,
        // 月租利润
        profits: _profits
    })
  }
}

var j = schedule.scheduleJob(rule, function(){
  //更新月租有效期
  ClientModel.find({}, function(err, data) {
    data.map((item) => {
        var currDateToDay = Utils.currDateToDay(new Date(), new Date(item.nextBillingDate))
        console.log('currDateToDay___'+currDateToDay)
        // 欠费25天后取消号码，只要余额是负数，就取消号，进行标识，充值如果是正数就取消标识，
        // 如果欠费时间超过25天就取消号码
        if (item.oweDay && item.oweDay > 25) {
            Nexmo.numberCancel({country: item.country.countryCode, msisdn: item.msisdn}) // 取消nexmo号码
            ClientModel.deleteOne({_id: item._id}, function(err,data) {
              console.log(err, data)
            }) // 移除数据库nexmo号码
        } else {
            //倒数0天还没扣到就直接取消号码
            if (parseInt(currDateToDay) === 0) {
                //如果余额小于说明是欠费
                if (item.remainingMoney < 0 ) {
                  ClientModel.updateOne({_id: item._id}, {$set:{ nextBillingDay: -1, oweDay:item.oweDay+1, oweDate:  new Date()}}, function(err,data) {
                    console.log(err,data)
                  })
                } else {
                  setDeduction(item, true)
                }
            } else {
              setDeduction(item, false)
            } 
        }
    });
  }).populate('country', {_id: 1, dialingPrefix:1, countryCode: 1, countryName: 1})
});
module.exports = app;